﻿using Handday.Erp.Core;
using Handday.Erp.Transfer.Enum;
using HandDay.Framework.Common.Services;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Handday.Erp.Transfer.Services.Imp
{
    /// <summary>
    ///  数据推送通用服务
    /// </summary>
    public class PublishCommonService : IPublishCommonService
    {
        private readonly ISplitTableInfo _splitTableInfo;
        private readonly IServiceProvider _serviceProvider;

        /// <summary>
        /// ctor
        /// </summary>
        public PublishCommonService(
            ISplitTableInfo splitTableInfo,
            IServiceProvider serviceProvider)
        {
            _splitTableInfo = splitTableInfo;
            _serviceProvider = serviceProvider;
        }

        /// <summary>
        /// 推送逻辑
        /// </summary>
        public async Task<ServiceResult> PublishAsync(ErpFeatureTypeEnum featureType, ulong corpId, DateTimeOffset dateTime)
        {
            if (corpId > 0)
            {
                _splitTableInfo.Suffix = corpId.ToString();
            }

            var publishServiceList = _serviceProvider.GetServices<IPublishExecuteService>().Where(m => m.FeatureType == featureType);
            foreach (var publish in publishServiceList)
            {
                await publish.ExecuteAsync(corpId, dateTime);
            }

            return ServiceResult.Succeed();
        }
    }
}
